import dayjs from "dayjs";
import { useEntityManager, useRedis } from "@sker/core";
import { AutoDevice, AutoDeviceWork, AutoTask } from "@sker/entities";
import { container } from "tsyringe";
import { TASK_TOKEN } from "./tokens";
import { WebSocket } from 'ws'
export async function checkDeviceIsBusy(uuid: string, event: string) {
    if (event === 'ping' || event === 'pong') {
        const status = await useRedis(5, async (r) => {
            return await r.get(uuid)
        })
        if (status === `0`) {
            return false;
        }
        return false;
    }
    const isBusy = await useEntityManager(async m => {
        const date = dayjs().format('YYYY-MM-DD')
        const taskToday = await m.findOne(AutoDeviceWork, { where: { uuid, date: date } })
        if (taskToday) {
            console.log(`set device status ${taskToday.status} type is ${event} uuid is ${uuid}`)
            await useRedis(5, async r => {
                await r.set(uuid, taskToday.status)
            });
            return taskToday.status === `0`
        } else {
            const task = m.create(AutoDeviceWork, {
                room: 0,
                red: 0,
                money: 0,
                success: 0,
                fail: 0,
                mood: 100,
                continuous_fail: 0,
                continuous_success: 0,
                pre: `unknown`,
                date: date,
                uuid: uuid,
                continuous_room_fail: 0,
                continuous_room_success: 0,
                status: `0`,
                type: 'leader'
            });
            console.log(`set device status ${task.status} type is ${event} uuid is ${uuid}`)
            await useRedis(5, async r => {
                await r.set(uuid, task.status)
            });
            await m.save(AutoDeviceWork, task)
            return true;
        }
    })
    return isBusy;
}
/**
 * 获取任务
 */
export async function getTask(uuid: string, event: string) {
    // 根据uuid和当前事件检测当前机器是否空闲
    const isBusy = await checkDeviceIsBusy(uuid, event)
    if (isBusy) {
        return false;
    }
    const tasks = container.resolveAll(TASK_TOKEN)
    const task = tasks.sort((a, b) => a.order - b.order).find(it => it.canRun())
    if (task) return task;
    return false;
}
/**
 * 执行任务
 * @param uuid 
 * @param event 
 * @param wss 
 * @returns 
 */
export async function runTask(uuid: string, event: string, wss: WebSocket) {
    if(event === 'FIND_RED_PACKET'){
        
    }
    // const tasks = container.resolveAll(TASK_TOKEN)
    // const finishTasks = tasks.filter(task => task.isFinishSign(event))
    // if (finishTasks && finishTasks.length > 0) {
    //     await Promise.all(finishTasks.map(task => task.finish(uuid)))
    //     return;
    // }
    // const task = await getTask(uuid, event)
    // if (!task) {
    //     return false;
    // }
    // const code = await task.getCode()
    // if (code) {
    //     wss.send(JSON.stringify({ type: "CLOUD_CODE", payload: code }))
    // }
    return true;
}

export async function onConnection(uuid: string, wss: WebSocket) {
    await useEntityManager(async m => {
        const device = await m.findOne(AutoDevice, { where: { device_uuid: uuid } })
        if (!device) return;
        if (device.type === 'leader') {
            const autoTask = await m.findOne(AutoTask, { where: { name: 'FindRedPacketTask' } })
            if (!autoTask) return;
            const interval = 60 * 1000 * 60 * 8;
            const delay = 0;
            const payload = {
                code: autoTask.code,
                id: autoTask.name,
                loopTimes: 0,
                interval: interval,
                delay: delay
            }
            console.log(`send code to leader client`)
            wss.send(JSON.stringify({ type: "CLOUD_CODE", payload: payload }))
            return;
        }
        if (device.type === 'worker') {
            const autoTask = await m.findOne(AutoTask, { where: { name: 'TakeRedPacketTask' } })
            if (!autoTask) return;
            const interval = 60 * 1000 * 60 * 8;
            const delay = 0;
            const payload = {
                code: autoTask.code,
                id: autoTask.name,
                loopTimes: 0,
                interval: interval,
                delay: delay
            }
            console.log(`send code to worker client`)
            wss.send(JSON.stringify({ type: "CLOUD_CODE", payload: payload }))
            return;
        }
    })
}

function random(min: number, max: number) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}